class Solution {
    int m = 0;
    int n = 0;
    int[] dx = {0, 0, 1, -1, 1, -1, 1, -1};
    int[] dy = {1, -1, 0, 0, 1, 1, -1, -1};

    public char[][] updateBoard(char[][] board, int[] click) {
        m = board.length;
        n = board[0].length;

        dfs(board, click);
        return board;
    }
    public void dfs(char[][] board, int[] click){
        int i = click[0];
        int j = click[1];
        // 游戏结束
        if(board[i][j] == 'M') {
            board[i][j] = 'X';
            return;
        }
        // 挖出空块
        if(board[i][j] == 'E'){
            int count = 0;
            for(int k = 0; k < 8; k++){
                int x = i + dx[k];
                int y = j + dy[k];
                // count > 0 有相邻地雷
                if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M'){
                    count++;
                }
            }
            // count == 0 没有相邻地雷
            if(count == 0){
                board[i][j] = 'B';
                for(int k = 0; k < 8; k++){
                    int x = i + dx[k];
                    int y = j + dy[k];
                    if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E'){
                        dfs(board, new int[] {x, y});
                    }
                }
            }else{
                board[i][j] = (char)('0' + count);
            }
        }
    }
}